package com.sharedmobility.servlet;

import com.google.gson.Gson;
import com.sharedmobility.dao.UserDAO;
import com.sharedmobility.model.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.annotation.WebServlet;

@WebServlet("/api/check-login")
public class CheckLoginServlet extends HttpServlet {
    private UserDAO userDAO;
    private Gson gson;

    @Override
    public void init() throws ServletException {
        userDAO = new UserDAO();
        gson = new Gson();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 获取当前会话
            HttpSession session = request.getSession(false);
            
            if (session == null) {
                // 未登录
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未登录");
                result.put("loggedIn", false);
                
                response.getWriter().write(gson.toJson(result));
                return;
            }

            // 获取用户ID
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                // 会话中没有用户ID
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未登录");
                result.put("loggedIn", false);
                
                response.getWriter().write(gson.toJson(result));
                return;
            }

            // 从数据库获取用户信息
            User user = userDAO.findById(userId);
            if (user == null) {
                // 用户不存在
                session.invalidate();
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "用户不存在");
                result.put("loggedIn", false);
                
                response.getWriter().write(gson.toJson(result));
                return;
            }

            // 检查用户状态
            if (user.getStatus() != 1) {
                // 用户被禁用
                session.invalidate();
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "账号已被禁用");
                result.put("loggedIn", false);
                
                response.getWriter().write(gson.toJson(result));
                return;
            }

            // 返回用户信息
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "已登录");
            result.put("loggedIn", true);
            
            Map<String, Object> userData = new HashMap<>();
            userData.put("id", user.getId());
            userData.put("username", user.getUsername());
            userData.put("role", user.getRole());
            userData.put("balance", user.getBalance());
            userData.put("creditScore", user.getCreditScore());
            
            result.put("data", userData);
            
            response.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            // 返回错误响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "检查登录状态失败：" + e.getMessage());
            result.put("loggedIn", false);
            
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write(gson.toJson(result));
        }
    }
} 